import argparse, pathlib, pypinyin, re

def bihua(word):
    if not hasattr(bihua, '_'):
        with open(pathlib.Path(__file__).parent / 'stroke.txt') as f: bihua._ = {a[0]: int(a[1:]) for a in f}
    return bihua._[word]

class Entry(str):
    def __lt__(*entries):
        heads = [(lambda a: re.match('【.+】', a)[0][1:-1])(e) for e in entries]
        pys = map(lambda a: pypinyin.pinyin(a, style=pypinyin.Style.TONE3), heads)
        for a, b, ap, bp in zip(*heads, *pys):
            if ap == bp:
                ab, bb = map(bihua, (a, b))
                if ab == bb:
                    if a == b: continue
                    return ord(a) < ord(b)
                return ab < bb
            return ap < bp

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--inplace', action='store_true')
parser.add_argument('dictname')
args = parser.parse_args()
with open(args.dictname) as f: moe = f.read()
moe = '\n'.join(sorted(Entry(e) for e in moe.split()))
if args.inplace:
    with open(args.dictname, 'w') as f: f.write(moe)
else: print(moe)
